package cn.stylefeng.mferp.core.util;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ReflectUtil {

    /**
     * * 获取属性名数组
     * 
     * @param object
     * @return
     */
    public static String[] getFiledName(Object object) {
        Field[] fields = object.getClass().getDeclaredFields();
        String[] fieldNamStrings = new String[fields.length];
        for (int i = 0; i < fieldNamStrings.length; i++) {
            fieldNamStrings[i] = fields[i].getName();
        }
        return fieldNamStrings;
    }


    /**
     * 
     * @Description 根据属性名 获取值（value）
     * @param name
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public static Object getFieldValueByName(String name, Object object) throws IllegalAccessException {
        try {
            // 获取obj类的字节文件对象
            Class c = object.getClass();
            // 获取该类的成员变量
            Field f = c.getDeclaredField(name);
            // 取消语言访问检查
            f.setAccessible(true);
            return f.get(object);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 设值
     * @param name
     * @param object
     * @param value
     * @throws IllegalAccessException
     */
    public static void setFieldValueByName(String name, Object object, Object value) throws IllegalAccessException {
        try {
            // 获取obj类的字节文件对象
            Class c = object.getClass();
            // 获取该类的成员变量
            Field f = c.getDeclaredField(name);
            boolean isFinal = Modifier.isFinal(f.getModifiers());//final常量不赋值
            if(isFinal) return;
            // 取消语言访问检查
            f.setAccessible(true);
            // 给变量赋值
            f.set(object, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 复制信息
     * @param origin
     * @param target
     */
    public static void copyValue(Object origin, Object target) {
        Field[] oFields = origin.getClass().getDeclaredFields();
        Field[] tFields = target.getClass().getDeclaredFields();
        for (Field tf : tFields) {
            String rfName = tf.getName();
            for (Field of : oFields) {
                String ofName = of.getName();
                if(StringUtils.isNotBlank(ofName) &&
                        StringUtils.isNotBlank(rfName) && ofName.equalsIgnoreCase(rfName)) {
                    try {
                        Object ov = getFieldValueByName(ofName, origin);
                        if(ov != null) {
                            setFieldValueByName(rfName, target, ov);
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
    }
}
